<template>
  <div class="strategy-wrapper" v-cloak>
    <v-header :title="pageTitle" :fixed="true" :opacity="headerOpacity">
      <ul class="header-right" slot="right">
        <li class="btn" @click.stop="toggleCollection">
          <i class="icon iconfont" :class="collectionType === 1 ? 'icon-collection-b' : 'icon-collection'" aria-hidden="true" style="font-size: 19px;"></i>
        </li>
        <li class="btn" @click.stop="toShare">
          <i class="icon iconfont icon-share" aria-hidden="true" style="font-size: 17px; padding-top: 3px;"></i>
        </li>
      </ul>
    </v-header>
    <div ref="main" v-if="!isLoadFail">
      <div class="head-img" v-lazy:backgroundImage="strategy.firstImg" :style="{paddingTop: paddingTop + 'px'}"></div>
      <div class="travels-title">
        <p>{{strategy.title}}</p>
        <div>官方出品</div>
      </div>
      <div class="box">
        <p class="title">攻略简介</p>
        <p class="desc">{{strategy.intro}}</p>
      </div>
      
      <ul :style="{paddingBottom: paddingBottom + 'px'}">
        <li v-for="(title, index1) in strategy.articleContent" :key="index1" class="box" @click="toStrategyDetail(index1)">
          <p class="title">{{title.content}}</p>
          <ul class="section">
            <li v-for="(section, index2) in title.list" :key="index2" v-if="section.type === 2" @click.stop="toStrategyDetail(index1, index2)">{{section.content}}</li>
          </ul>
        </li>
      </ul>
    </div>

    <load-fail v-if="isLoadFail" :tip="tip" style="height: auto; padding-top: 0px; margin-top: 210px;"></load-fail>

    <share v-model="showShare" :title="shareContent.title" :desc="shareContent.desc" :thumbUrl="shareContent.thumbUrl" :linkUrl="shareContent.linkUrl"></share>

    <div class="category-btn" @click.stop="showCategory = true">目录</div>
    <!-- 目录 -->
    <div v-transfer-dom>
      <popup v-model="showCategory" position="right" width="60%" class="popup-wrapper">
        <div class="category">
          <p class="cate-top"  :style="{paddingTop: paddingTop + 20 + 'px'}">- 目录 -</p>
          <ul :style="{paddingBottom: paddingBottom + 'px'}">
            <li @click="showCategory = false" style="color: #fff">
              <p class="cate-title">攻略简介</p>
            </li>
            <li v-for="(title, index1) in strategy.articleContent" :key="index1"  @click="toStrategyDetail(index1)">
              <p class="cate-title">{{title.content}}</p>
              <ul class="cate-section">
                <li v-for="(section, index2) in title.list" :key="index2" v-if="section.type === 2" @click.stop="toStrategyDetail(index1, index2)">
                  <p>{{section.content}}</p>
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </popup>
    </div>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import LoadFail from '@/components/load-fail/load-fail'
import Share from '@/components/share/share'
import { TransferDom, Popup } from 'vux'

import axios from '@/api/axiosApi'
import { isIphoneX } from '@/assets/js/brower'
import { localUser } from '@/assets/js/local'
import { QINIU_PREFIX } from '@/api/config'
// import { QINIU_PREFIX, APP_DOWNLOAD_PATH } from '@/api/config'
import defaultAvatar from '@/assets/img/default_avatar.png'
import { on } from '@/assets/js/dom'
import { handleBackMixin } from '@/assets/js/mixin'

export default {
  name: 'Strategy',
  mixins: [handleBackMixin],
  data () {
    return {
      isLoadFail: false,
      tip: '',
      pageTitle: '',
      headerOpacity: 0,
      collectionType: 0,
      showShare: false,
      showCategory: false,
      shareContent: {},
      strategy: {},
      allPopupModels: ['showCategory', 'showShare']
    }
  },
  directives: {
    TransferDom
  },
  components: {
    VHeader, LoadFail, Share, Popup
  },
  created() {
    this.paddingTop = 24
    this.paddingBottom = 0
    if (isIphoneX()) {
      this.paddingTop = 34
      this.paddingBottom = 34
    }

    this._getStrategy()
  },
  mounted() {
    on(this.$el, 'scroll', () => {
      const scrollTop = this.$el.scrollTop
      if (scrollTop > 210) {
        this.pageTitle = this.strategy.title.substr(0, 6)
      } else {
        this.pageTitle = ''
      }
      this.headerOpacity = scrollTop / 210
    })
  },
  methods: {
    _getStrategy() {
      axios.get(this, '/v1/playStrategy', {
        id: this.$route.params.strategyId
      }, (data) => {
        if (data == null || data.length === 0) {
          this.tip = '页面加载失败<br>没有找到该攻略，或者该攻略已下架'
          this.isLoadFail = true
          return
        }

        this.isLoadFail = false
        let tmpHeadUrl = defaultAvatar
        if (data[0].userHeadUrl) {
          if (data[0].userHeadUrl.indexOf(QINIU_PREFIX) > -1) {
            tmpHeadUrl = data[0].userHeadUrl + '-bheader'
          } else {
            tmpHeadUrl = data[0].userHeadUrl
          }
        }
        if (data[0].firstImg && data[0].firstImg.indexOf(QINIU_PREFIX) > -1) {
          data[0].firstImg += '-w200'
        }

        data[0].userHeadUrl = tmpHeadUrl
        data[0].travelTime = this.moment(data[0].travelTime).format('YYYY/MM/DD')
        data[0].articleContent = JSON.parse(data[0].articleContent)
        // 处理数据格式
        const tmp = []
        let currentIndex = -1
        data[0].articleContent.forEach((item, index) => {
          if (item.type === 1) {
            item.list = []
            tmp.push(item)
            currentIndex++
          } else {
            tmp[currentIndex].list.push(item)
          }
        })
        data[0].articleContent = tmp
        this.strategy = data[0]

        this._getStatus()
        this._viewStrategy()
      }, (e) => {
        this.tip = '页面加载失败<br>网络错误'
        this.isLoadFail = true
      })
    },
    _getStatus() {
      const userId = localUser.get('id')
      if (userId != null) {
        // 点赞和收藏状态
        axios.get(this, '/v1/messageRecord/' + userId + '/' + this.$route.params.strategyId, null, (data) => {
          if (data) {
            this.starType = data.starType
            this.collectionType = data.collectionType
          }
        }, null, false)
      }
    },
    _viewStrategy() {
      const userId = localUser.get('id')
      if (userId != null) {
        axios.post(this, '/v1/messageRecord', {
          userId: userId,
          targetId: this.strategy.id,
          type: 3
        }, (data) => {
        }, null, false)
      }
    },
    toggleCollection () {
      // 切换收藏状态
      if (localUser.get('id') == null) {
        this.$vux.toast.text('请先登录！', 'middle')
        setTimeout(() => {
          this.$router.push('/login')
        }, 200)
        return
      }
      if (this.strategy == null) {
        return
      }
      if (this.collectionType === 0) {
        this.collectionType = 1
      } else {
        this.collectionType = 0
      }
      axios.put(this, '/v1/messageRecord', {
        userId: localUser.get('id'),
        targetId: this.strategy.id,
        collectionType: this.collectionType,
        type: 3
      }, (res) => {
        if (this.collectionType === 0) {
          this.$vux.toast.text('取消收藏！')
        } else {
          this.$vux.toast.text('收藏成功！')
        }
      })
    },
    toShare() {
      this.showShare = true
      this.shareContent = {
        title: this.strategy.title,
        desc: this.strategy.intro.substr(0, 30),
        thumbUrl: this.strategy.firstImg,
        // linkUrl: APP_DOWNLOAD_PATH
        linkUrl: this.$route.path
      }
    },
    toStrategyDetail(titleIndex, sectionIndex) {
      this.$router.push({
        path: `/address/strategyDetail/${this.$route.params.strategyId}`,
        query: {
          titleIndex,
          sectionIndex
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.box
  padding 8px 16px
  .title
    font-size 16px
    color #333
    font-weight bold
    margin-bottom 16px
    position relative
    padding-left 16px
    &:before
      position absolute
      left 0
      top 4px
      bottom 4px
      width 4px
      border-radius 4px
      background-color $color-theme
      content ''
      display block
  .desc
    font-size 15px
    color #333
    line-height 1.6
    text-align justify
.strategy-wrapper
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  background-color #ffffff
  z-index 100
  overflow-x hidden
  overflow-y auto
  -webkit-overflow-scrolling touch
  -webkit-box-sizing border-box
.header-right
  display flex
  align-items center
  .btn
    extend-click()
    i
      font-size 18px
      color #fff
  li
    margin-left 20px
.head-img
  height 210px
  background-size cover
  background-position center
  background-repeat no-repeat
.travels-title
  display flex
  justify-content space-between
  padding 16px
  padding-bottom 12px
  p
    font-size 24px
    color #333
  div
    font-size 10px
    line-height 22px
    height 20px
    min-width 55px
    text-align center
    color #29c529
    border 0.5px solid #29c529
    border-radius 2px
    margin-top 8px
    margin-left 8px
.section
  li
    float left
    width 50%
    no-wrap-n(2)
    font-size 15px
    color #333
    margin-bottom 12px
  &:after
    content ''
    display block
    clear both
.category-btn
  position fixed
  bottom 95px
  right -20px
  height 40px
  line-height 40px
  border-radius 20px
  padding-left 20px
  padding-right 30px
  background $color-theme
  color #fff
  box-shadow 0 0 10px #d0d0d0
  font-size 16px
.popup-wrapper
  background $color-theme
.category
  color #ececec
  height 100%
  padding-left 16px
  font-size 15px
  .cate-top
    font-size 24px
    font-weight bold
    text-align center
    padding-top 20px
    padding-bottom 16px
  .cate-title
    padding-left 4px
  .cate-section
    text-indent 2rem
    font-size 14px
    p
      line-height 38px
      height 38px
  li
    p
      border-bottom 0.5px solid rgba(255, 255, 255, 0.6)
      height 45px
      line-height 45px
      no-wrap()
</style>
